﻿#region Using directives

using System;
using System.IO;
using System.Collections.Generic;
using System.Text;

#endregion

namespace Weazel.Badger.Vhdl
{
  public class DesignFile
  {
    // name of file to save result to
    private string fileName = null;
    public string FileName
    {
      get
      {
        return fileName;
      }
    }

    private List<string> designUnit = new List<string>();
    public List<string> DesignUnit
    {
      get
      {
        return designUnit;
      }

      set
      {
        designUnit = value;
      }
    }

    private List<Entity> entities = new List<Entity>();
    public List<Entity> Entities
    {
      get
      {
        return entities;
      }

      set
      {
        entities = value;
      }
    }


    public void AddEntity(Entity e)
    {
      if(!(entities.Contains(e)))
        entities.Add(e);
    }

    public DesignFile(string fileName)
    {
			this.fileName = fileName.EndsWith(".vhd") ? fileName : fileName + ".vhd";
    }
    
    public void Resolve()
    {
      foreach (Entity e in entities)
        e.Resolve();
    }

    public void Verify(ref List<VerifyMessage> messages)
    {
      foreach (Entity e in entities)
        e.Verify(ref messages);
    }




    public void Write(System.CodeDom.Compiler.IndentedTextWriter writer)
    {
      foreach (string s in designUnit)
        writer.WriteLine(s);

      if (designUnit.Count > 0)
        writer.WriteLine();

      foreach (Entity e in entities)      
        e.Write(writer);
      
      writer.WriteLine("-- end of file");
    }

    /// <summary>
    /// Write this file to disk. 
    /// </summary>
    /// <param name="outputDirectory">Directory where to write this file or null to use the
    /// current workning directory</param>
    public void Write(string outputDirectory)
    {
      // get a valid file name
      string outputDestination = 
          outputDirectory != null ? outputDirectory + "//" + fileName  
        : fileName;

      FileStream file = null;
      StreamWriter streamWriter = null;
      System.CodeDom.Compiler.IndentedTextWriter writer = null;

      try
      {
        file = File.Create(outputDestination);
        streamWriter = new StreamWriter(file);
        writer = new System.CodeDom.Compiler.IndentedTextWriter(streamWriter);        

        List<VerifyMessage> messages = new List<VerifyMessage>();
        Verify(ref messages);

        foreach (VerifyMessage message in messages)
          Console.WriteLine(message);

        Write(writer);
      }
      finally
      {
        if (writer != null)
          writer.Close();

        if (streamWriter != null)
          streamWriter.Close();

        if (file != null)
          file.Close();
      }
    }
  }
}
